package ans.p59;

/**
 * #      59
 * 名称   螺旋矩阵 II
 * 链接   https://leetcode-cn.com/problems/spiral-matrix-ii
 * 题解   [1230](https://leetcode-cn.com/problems/spiral-matrix-ii/solution)
 * 通过率 80.1%
 * 难道   中等
 */

public class Solution {
    public static int[][] delta = new int[][]{
            new int[]{1, 0},
            new int[]{0, 1},
            new int[]{-1, 0},
            new int[]{0, -1},
    };

    public int[][] generateMatrix(int n) {
        int[][] ans = new int[n][n];
        int x = -1, y = 0;
        int mode = 3;
        for (int i = 1; i <= n * n; i++) {
            int[] d = delta[mode];
            if (0 > x + d[0] || x + d[0] >= n || 0 > y + d[1] || y + d[1] >= n || ans[y + d[1]][x + d[0]] != 0) {
                mode = (mode + 1) % 4;
                d = delta[mode];
            }
            x = x + d[0];
            y = y + d[1];
            ans[y][x] = i;
        }
        return ans;
    }
}